<template>
	<view class="withdraw-container">
		<!-- 提现到 -->
		<view class="withdraw-to">
			<text class="section-title">提现至</text>
			<view class="bank-card-section" @tap="goToAddCard" v-if="cardList.length === 0">
				<text class="add-text">添加银行卡</text>
				<text class="arrow">›</text>
			</view>
			<view class="card-list" v-else>
				<view class="card-item" :class="[selectedCard && selectedCard.id === card.id ? 'active' : '']"
					v-for="card in cardList" :key="card.id" @tap="selectCard(card)">
					<view class="card-info">
						<text class="bank-name">{{card.accountName}}</text>
						<text class="card-number">{{formatCardNumber(card.cardNumber)}}</text>
					</view>
					<text class="check-icon" v-if="selectedCard && selectedCard.id === card.id">✓</text>
				</view>
				<view class="add-more" @tap="goToAddCard">
					<text class="add-text">添加新卡</text>
					<text class="arrow">›</text>
				</view>
			</view>
		</view>

		<!-- 提现金额 -->
		<view class="amount-section">
			<text class="amount-label">提现金额</text>
			<view class="amount-input-wrap">
				<text class="currency">¥</text>
				<input type="digit" v-model="amount" class="amount-input" placeholder="请输入提现金额" @input="calculateFee" />
			</view>
			<view class="fee-info" v-if="amount">
				<text>手续费：¥{{serviceFee}}</text>
				<text>实际到账：¥{{actualAmount}}</text>
			</view>
			<view class="balance-info">
				<text>可提现余额 ¥{{availableBalance}}</text>
				<text class="withdraw-all" @tap="withdrawAll">全部提现</text>
			</view>
		</view>

		<!-- 提现说明 -->
		<view class="withdraw-tips">
			<view class="tip-item">1. 单人单日最多提现5次，单日总提现额度5k。</view>
			<view class="tip-item">2. 提现金额最小1元,提现收取{{serviceRate}}%手续费。</view>
			<view class="tip-item">3. 提款中如遇到任何问题请联系客服（微信同号）</view>
		</view>

		<!-- 提现按钮 -->
		<view class="bottom-btn">
			<button class="withdraw-btn" :disabled="!canWithdraw" @tap="handleWithdraw">
				提现
			</button>
		</view>
	</view>
</template>

<script>
	import {
		my
	} from '@/api/wallet/wallet.js'
	import {
		addWalletWithdraw
	} from '@/api/wallet/walletWithdraw.js'
	import {
		listMyCards
	} from '@/api/wallet/bankCard.js'

	import {
		getConfigKey
	} from '@/api/system/config.js'

	export default {
		data() {
			return {
				selectedCard: null,
				cardList: [],
				amount: '',
				availableBalance: '0.00',
				serviceRate: 0, //提现手续费费率
				serviceFee: '0.00', // 手续费
				actualAmount: '0.00', // 实际到账金额
			}
		},
		computed: {
			canWithdraw() {
				const amount = parseFloat(this.amount)
				return this.selectedCard && 
					this.selectedCard.id &&
					amount &&
					amount >= 1 && // 最小提现金额1元
					amount <= parseFloat(this.availableBalance)
			}
		},
		onLoad() {
			this.getSysConfig()
			this.getWalletInfo()
			this.getMyCards()
		},
		methods: {
			// 获取系统手续费配置
			async getSysConfig() {
				try {
					const res = await getConfigKey('sys.withdraw.service.rate')
					console.log('getSysConfig', res)
					if (res.code === 200) {
						this.serviceRate = res.data
					}
				} catch (error) {
					console.error('获取钱包信息失败:', error)
				}
			},
			// 获取钱包信息
			async getWalletInfo() {
				try {
					const res = await my()
					if (res.code === 200) {
						this.availableBalance = res.data.availableBalance
					}
				} catch (error) {
					console.error('获取钱包信息失败:', error)
				}
			},
			// 获取我的银行卡
			async getMyCards() {
				try {
					const res = await listMyCards()
					if (res.code === 200) {
						this.cardList = res.data || []
						// 如果有卡片但未选择，默认选中第一张
						if (this.cardList.length > 0 && !this.selectedCard) {
							this.selectedCard = this.cardList[0]
						}
					}
				} catch (error) {
					console.error('获取银行卡失败:', error)
				}
			},
			goToAddCard() {
				uni.navigateTo({
					url: '/pages/wallet/add-bank-card'
				})
			},
			// 格式化银行卡号
			formatCardNumber(number) {
				if (!number) return ''
				return number.replace(/(\d{4})/g, '$1 ').trim()
			},
			// 计算手续费和实际到账金额
			calculateFee() {
				if (!this.amount || isNaN(this.amount)) {
					this.serviceFee = '0.00'
					this.actualAmount = '0.00'
					return
				}
				
				const amount = parseFloat(this.amount)
				if (amount < 1) {
					this.serviceFee = '0.00'
					this.actualAmount = '0.00'
					return
				}
				
				// 计算手续费
				const fee = (amount * this.serviceRate / 100).toFixed(2)
				this.serviceFee = fee
				
				// 计算实际到账金额
				this.actualAmount = (amount - parseFloat(fee)).toFixed(2)
			},
			// 全部提现
			withdrawAll() {
				this.amount = this.availableBalance
				this.calculateFee()
			},
			// 提现操作
			async handleWithdraw() {
				if (!this.canWithdraw || !this.selectedCard) {
					uni.showToast({
						title: '请选择银行卡并输入不小于1元的提现金额',
						icon: 'none'
					})
					return
				}

				try {
					const withdrawData = {
						amount: this.amount,
						serviceFee: this.serviceFee,
						serviceRate: this.serviceRate,
						inAmount: this.actualAmount,
						cardId: this.selectedCard.id
					}
					const res = await addWalletWithdraw(withdrawData)
					if (res.code === 200) {
						uni.showToast({
							title: '提现申请成功',
							icon: 'success'
						})
						setTimeout(() => {
							// 获取上一页实例
							const pages = getCurrentPages()
							const prevPage = pages[pages.length - 2]
							// 如果上一页是钱包页面，刷新数据
							if (prevPage && prevPage.route === 'pages/wallet/index') {
								prevPage.$vm.getWalletInfo()
							}
							uni.navigateBack()
						}, 1500)
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '提现失败',
						icon: 'none'
					})
				}
			},
			// 选择银行卡
			selectCard(card) {
				this.selectedCard = card
			}
		}
	}
</script>

<style lang="scss" scoped>
	.withdraw-container {
		min-height: 100vh;
		background: #f5f5f5;
		padding: 20rpx;

		.withdraw-to {
			background: #fff;
			border-radius: 12rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.section-title {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 20rpx;
				display: block;
			}

			.bank-card-section {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 0;

				.add-text {
					font-size: 32rpx;
					color: #333;
				}

				.arrow {
					font-size: 32rpx;
					color: #999;
				}
			}

			.card-list {
				background: #fff;
				border-radius: 12rpx;
				margin-top: 20rpx;

				.card-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx;
					border-bottom: 1rpx solid #eee;

					&.active {
						background: #f0f9f0;

						.bank-name {
							color: #4CAF50;
						}
					}

					.card-info {
						.bank-name {
							font-size: 32rpx;
							color: #333;
							font-weight: bold;
							margin-bottom: 10rpx;
							display: block;
						}

						.card-number {
							font-size: 28rpx;
							color: #666;
						}
					}

					.check-icon {
						font-size: 40rpx;
						color: #4CAF50;
					}
				}

				.add-more {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx;

					.add-text {
						font-size: 28rpx;
						color: #4CAF50;
					}

					.arrow {
						font-size: 32rpx;
						color: #999;
					}
				}
			}
		}

		.amount-section {
			background: #fff;
			border-radius: 12rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.amount-label {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 20rpx;
				display: block;
			}

			.amount-input-wrap {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #eee;

				.currency {
					font-size: 40rpx;
					color: #333;
					margin-right: 20rpx;
				}

				.amount-input {
					flex: 1;
					font-size: 32rpx;
				}
			}

			.fee-info {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 20rpx;
				padding-top: 20rpx;
				border-top: 1rpx solid #eee;
				font-size: 26rpx;
				color: #666;
			}

			.balance-info {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 20rpx;
				font-size: 26rpx;
				color: #999;

				.withdraw-all {
					color: #4CAF50;
				}
			}
		}

		.withdraw-tips {
			padding: 30rpx;

			.tip-item {
				font-size: 26rpx;
				color: #999;
				margin-bottom: 10rpx;

				&:last-child {
					margin-bottom: 0;
				}
			}
		}

		.bottom-btn {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			padding: 20rpx;
			background: #fff;

			.withdraw-btn {
				width: 100%;
				height: 88rpx;
				line-height: 88rpx;
				background: #4CAF50;
				color: #fff;
				border-radius: 44rpx;
				font-size: 32rpx;

				&[disabled] {
					opacity: 0.5;
				}
			}
		}
	}
</style>